﻿using Autofac;
using BCVP.Net8.Extension.aop;
using BCVP.Net8.Repository.Base;
using BCVP.Net8.Repository.UnitOfWorks;
using BCVP.Net8.Repository.User;
using BCVP.Net8.Service.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BCVP.Net8.Extension.autofac
{
    public class AutofacModuleRegister : Autofac.Module
    {
        /// <summary>
        /// 通过autofac对程序集中的类进行依赖注入
        /// </summary>
        /// <param name="builder"></param>
        protected override void Load(ContainerBuilder builder)
        {
            var basePath = AppContext.BaseDirectory;

            var serviceDllFile = Path.Combine(basePath, "BCVP.Net8.Service.dll");
            var repositoryDllFile = Path.Combine(basePath, "BCVP.Net8.Repository.dll");

            var aopType = new List<Type> { typeof(ServiceAOP) };
            builder.RegisterType<ServiceAOP>();

            // 注册服务
            builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency();
            builder.RegisterGeneric(typeof(BaseService<,>)).As(typeof(IBaseService<,>)).InstancePerDependency();

            // 注册sqlsugar事务服务
            builder.RegisterType(typeof(UnitOfWorkManage)).As(typeof(IUnitOfWorkManage)).InstancePerDependency();

            // 注册IUserRepository和UserRepository服务
            builder.RegisterType(typeof(UserRepository)).As(typeof(IUserRepository)).InstancePerDependency();


            //  获取Service.dll 程序集服务,并注册
            var assemblysService = Assembly.LoadFrom(serviceDllFile);
            builder.RegisterAssemblyTypes(assemblysService)
                .AsImplementedInterfaces()
                .PropertiesAutowired()
                .InstancePerDependency();

            // 获取Repository.dll 程序集服务,并注册
            var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
            builder.RegisterAssemblyTypes(assemblysService)
                .AsImplementedInterfaces()
                .PropertiesAutowired()
                .InstancePerDependency();
        }
    }

}
